//
//  BlogDetailVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/11.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import MJRefresh

class BlogDetailVC: BaseVC {
    
    @IBOutlet weak var replayView: UIView!
    @IBOutlet weak var replayLabel: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    
    var viewModel:BlogDetailViewModel!
    
    
    init(_ blog:Blog) {
        
        viewModel = BlogDetailViewModel()
        viewModel.blog = blog
        
        super.init(nibName: "BlogDetailVC", bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    private func setupUI() {
        
        tableView.register(UINib(nibName: "BlogCommentCell", bundle: nil), forCellReuseIdentifier: "BlogCommentCell")
        tableView.register(UINib(nibName: "CommentNoDataCell", bundle: nil), forCellReuseIdentifier: "CommentNoDataCell")
        
        tableView.register(UINib(nibName: "BlogCell", bundle: nil), forCellReuseIdentifier: "BlogCell")
        
        tableView.estimatedRowHeight = 140;
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .none
        
        tableView.tableHeaderView = placeholderHeadView()
        
        tableView.sectionHeaderHeight = 8.0
        tableView.sectionFooterHeight = 0.1
        
        replayLabel.layer.borderWidth = 0.5
        replayLabel.layer.cornerRadius = 5
        replayLabel.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        
        replayView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showCommentVC)))
    }
    
    @objc func showCommentVC() {
        
        
        comment(to: nil)
    }
    
    
    private func comment(to:User?) {
        
        let commentVC = CommentVC()
        
        commentVC.blogid = viewModel.blog?._id
        commentVC.toUser = to
        
        commentVC.show(self)
        
        commentVC.commentSuccess = {
            
            [weak self] comment in
            guard let `self` = self else { return }
            
            self.viewModel.comments.add(comment)
            self.viewModel.blog?.comment_count = (self.viewModel.blog?.comment_count ?? 0) + 1
            
            self.tableView.reloadData()
        }
        
    }
    
    private func setupData() {
        
        //        NetAPI.blogdetail(bid: (viewModel.blog?._id)!).request(Blog.self,dealJson: "blog") { (response, errmsg) in
        //
        //            guard let blog = response as? Blog else {
        //
        //                self.showToast(errmsg)
        //                return
        //            }
        //
        //            self.viewModel.blog = blog
        //            self.tableView.reloadData()
        //        }
        
        self.title = "动态详情"
        
        viewModel.loadFinished = {
            
            [weak self] error in
            guard let `self` = self else { return }
            
            if let error = error {
                
                self.showToast(error)
            }
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.resetNoMoreData()
            
            
            if self.viewModel.comments.count == 0 || self.viewModel.comments.count % kPerPage != 0 {
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            } else {
                
                self.tableView.mj_footer.endRefreshing()
            }
            
            self.tableView.reloadData()
        }
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.viewModel.reloadData()
        })
        
        let footer = MJRefreshAutoFooter(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.viewModel.getMoreComment()
        })
        tableView.mj_footer = footer
        
        tableView.mj_header.beginRefreshing()
        
    }
    
    private func placeholderHeadView() -> UIView {
        
        let headview = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 8))
        headview.backgroundColor = .clear
        
        return headview
    }
}

extension BlogDetailVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 1 {
            return viewModel.comments.count > 0 ? viewModel.comments.count : 1
        }
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "BlogCell") as! BlogCell
            cell.setBlog(viewModel.blog!)
            
            cell.delegate = self
            
            cell.reloadCell = {
                
                [weak self] cell in
                guard let `self` = self else { return }
                
                guard let idp = tableView.indexPath(for: cell) else { return }
                
                self.tableView.reloadRows(at: [idp], with: UITableViewRowAnimation.none)
            }
            
            return cell
        }
        
        if indexPath.row >= viewModel.comments.count {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "CommentNoDataCell")
            
            return cell!
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "BlogCommentCell") as! BlogCommentCell
        
        let comment = viewModel.comments[indexPath.row] as! Comment
        
        cell.comment = comment
        
        cell.pressedUser = {
            
            [weak self] user in
            guard let `self` = self else { return }
            
            let userBlogVC = BlogOrUserListVC(pageType: .auser, userid: user?._id)
            
            self.navigationController?.pushViewController(userBlogVC, animated: true)
        }
        
        cell.longPressComment = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if let remark = comment.remark {
                
                let pb = UIPasteboard.general
                
                pb.string = remark
                
                self.showToast("内容已复制到粘贴板")
            }
        }
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 0 {
            return
        }
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let comment = viewModel.comments[indexPath.row] as? Comment else { return }
        
        self.comment(to: comment.comment_user_info)
        
    }
}

extension BlogDetailVC : BlogCellDelegagte {
    
    
    func blogCell(cell:BlogCell,userid:Int?) {
        
        let userBlogVC = BlogOrUserListVC(pageType: .auser, userid: userid)
        
        self.navigationController?.pushViewController(userBlogVC, animated: true)
    }
    
    func blogCell(cell:BlogCell, need present:UIViewController) {
        
//        if present.isKind(of: LLTVideoPlayerVC.self) {
//            
//            self.llt_present(present, animated: LLTTransitionAnimationType.sysCameraIrisHollowOpen)
//            
//            return
//        }
        
        self.present(present, animated: true, completion: nil)
    }
    
    func blogCell(cell:BlogCell, action:ActionType, blog:Blog) {
        
        if action == .map {
            
            self.navigationController?.popToRootViewController(animated: true)
            NotificationCenter.default.post(name: kBackMapReloadNotifationName, object: nil, userInfo: [kNotifationNameObj:blog])
            
            return
        }
        
        if action == .comment {
            
            self.showCommentVC()
            
            return
        }
        
        if action == .auth {
            
            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            
            if blog.user_id == AppManager.share.user?._id {
                
                alertVC.addAction(UIAlertAction(title: "设为仅自己可见", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    self.changeBlogStatus(cell: cell, blog: blog, status: 11)
                }))
                
                alertVC.addAction(UIAlertAction(title: "设为所有人可见", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    self.changeBlogStatus(cell: cell, blog: blog, status: 0)
                }))
                
                //                alertVC.addAction(UIAlertAction(title: "删除", style: .destructive, handler: {
                //
                //                    [weak self] _ in
                //                    guard let `self` = self else { return }
                //
                //                    self.deleteBlog(cell: cell, blog: blog)
                //                }))
            } else {
                
                alertVC.addAction(UIAlertAction(title: "投诉", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    let reportVC = ReportVC(style: .plain)
                    
                    reportVC.bid = blog._id
                    
                    self.navigationController?.pushViewController(reportVC, animated: true)
                    
                }))
            }
            
            alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            
            self.present(alertVC, animated: true, completion: nil)
            
        }
    }
    
    private func changeBlogStatus(cell:BlogCell, blog:Blog, status:Int) {
        
        if blog.status != status {
            
            NetAPI.bloghide(bid: blog._id!, status: status).request {
                
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                
                if let msg = errmsg {
                    
                    self.showToast(msg)
                    return
                }
                
                self.showToast("修改成功")
                
                blog.status = status
                
                guard let indexpath = self.tableView.indexPath(for: cell) else { return }
                
                self.tableView.reloadRows(at: [indexpath], with: UITableViewRowAnimation.automatic)
                
            }
        }
        
    }
}

